const Seneca = require('seneca');
const seneca = Seneca().use('seneca-as-promised');
const Lock = require("./Lock.js");


let map = {};

function lock() {

    this.add({
        cmd: 'acquire'
    }, (msg, done) => {
        let key = msg.key;
        if (!key) {
            done("缺少参数key");
        }
        let lock = map[key];
        if (!lock) {
            lock = new Lock(22222);
            map[key] = lock;
        }
        lock.acquire().then(() => {
            done();
        });
    });
    this.add({
        cmd: 'release'
    }, (msg, done) => {
        let key = msg.key;
        if (!key) {
            done("缺少参数key");
        }
        let lock = map[key];
        if (!lock) {
            done("没有锁，不能释放");
        }
        lock.release();
        done();
    });
}
seneca.use(lock, {
        role: "lock"
    })
    .listen({
        type: 'tcp',
        port: 8261
    });
